package cn.lau.demo.util;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author War horse imwarhorse@aliyun.com
 * Date: 2020/12/24
 * Description: Http工具包
 * 包含获取http request中的指定字段值
 */

public class HttpUtil {

	/**
	 * 获取http request中指定的字段值
	 *
	 * @param servletRequest
	 * @param header         字段key name
	 * @return 值
	 */
	public static String getHeaderVal(ServletRequest servletRequest, String header) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String val;

		// null.trim()会报错！！
		val = request.getHeader(header);
		if (null == val || "".equals(val)) {
			// 从request parameters中获取
			val = request.getParameter(header);
			if (null == val || "".equals(val)) {
				Cookie[] cookies = request.getCookies();
				if (cookies == null) return val;
				for (Cookie cookie : cookies) {
					if (header.equals(cookie.getName())) {
						val = cookie.getValue();
						break;
					}
				}
			}
		}
		return val;
	}

}
